//
//  BizMenuCollectionViewFlowLayout.m
//  YYZB
//
//  Created by 顾悦 on 16/8/8.
//
//

#import "BizMenuCollectionViewFlowLayout.h"

@implementation BizMenuCollectionViewFlowLayout

- (instancetype)init {
    if (self = [super init]) {
        self.sectionInset = UIEdgeInsetsMake(10.0f, 10.0f, 10.0f, 10.0f);
        self.minimumInteritemSpacing = 10.0f;
        self.minimumLineSpacing = 10.0f;
    }
    
    return self;
}

#pragma mark - Private Helper Methods

-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)attributes
{
    // Check for representedElementKind being nil, indicating this is a cell and not a header or decoration view
    if (attributes.representedElementKind == nil)
    {
        NSIndexPath *indexPath = attributes.indexPath;
        CGFloat padding = 10;
        CGFloat leftCenterX = attributes.frame.size.width * 0.5 + padding;
        CGFloat rightCenterX = attributes.frame.size.width * 1.5 + 2 * padding;
        if (indexPath.item == 0) {
            attributes.center = CGPointMake(leftCenterX, attributes.frame.size.height * 0.5 + padding);
        } else if (indexPath.item == 1) {
            attributes.center = CGPointMake(rightCenterX, attributes.frame.size.height * 0.5 + padding);
        } else if (indexPath.item == 2) {
            attributes.center = CGPointMake(rightCenterX, attributes.frame.size.height * 1.5 + 2 * padding);
        } else {
            CGFloat x = indexPath.item % 2 ? leftCenterX : rightCenterX;
            NSInteger factor = indexPath.item % 2 ? (indexPath.item + 1) / 2 + 1 : (indexPath.item) / 2 + 1;
            CGFloat y = attributes.frame.size.height * (factor - 0.5) + factor * padding;
            attributes.center = CGPointMake(x, y);
        }
        attributes.frame = CGRectIntegral(attributes.frame);
    }
}

#pragma mark - Overridden Methods

#pragma mark Cell Layout

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *attributesArray = [super layoutAttributesForElementsInRect:rect];
    
    NSMutableArray *newAttributesArray = [NSMutableArray array];
    
    for (UICollectionViewLayoutAttributes *attributes in attributesArray)
    {
        [self applyLayoutAttributes:attributes];
    }
    
    attributesArray = [attributesArray arrayByAddingObjectsFromArray:newAttributesArray];
    
    return attributesArray;
}

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *attributes = [super layoutAttributesForItemAtIndexPath:indexPath];
    
    [self applyLayoutAttributes:attributes];
    
    return attributes;
}

@end
